<style>
.orderMessage {
  width: 150px;
  text-align: left;
  font-weight: bold;
}

#content:hover {
  cursor: pointer;
}

.el-dialog__title {
  font-weight: bold;
  font-size: 30px;
}

#order > .el-form-item {
  margin-bottom: 0
}

.el-divider--vertical {
  vertical-align: top;
  height: 200px;
  color: black;
}
</style>
<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="运动类别">
        <el-cascader v-model="categoryChoice" :options="categoryList"/>
      </el-form-item>
      <el-form-item label="日期">
        <el-tabs v-model="timeChoice">
          <el-tab-pane v-for="day in date" :label="day" :name="day">
          </el-tab-pane>
        </el-tabs>
        <el-table :data="orderList" :header-cell-style="{'text-align':'center'}" ref="choice"
                  :cell-style="{'text-align':'center'}" @cell-click="cellHandleclick">
          <el-table-column label="时间段" prop="time" width="200">
            <template slot-scope="{ row }">
              <div @click.stop>
                {{ row.time }}
              </div>
            </template>
          </el-table-column>

          <el-table-column v-for="courtName in courtList" width="100" :label="courtName.name" :prop="courtName.name">
            <template slot="header">
              <el-tooltip placement="top">
                <div slot="content">
                  <el-image style="width: 100px; height: 100px" :src="courtName.url" fit="fill"/>
                </div>
                <span>{{ courtName.name }}</span>
              </el-tooltip>
            </template>
            <template slot-scope="{ row }">
              <div id="content" :style="getCellStyles(row, courtName.name)">
                {{ row[courtName.name] }}
              </div>
            </template>
          </el-table-column>
        </el-table>

      </el-form-item>
    </el-form>


    <el-divider/>
    <el-dialog :visible.sync=orderDialog title="已拟定订单" width="700px" center>
      <div style="text-align: center;margin-left: 15px;">
        <div style="display: inline-block;margin-left: 10px">
          <vue-qr :text="order.amount"/>
        </div>
        <el-divider style="display: inline-block" direction="vertical"/>
        <div id="order" style="display: inline-block;vertical-align: top;">
          <el-form :model="order" label-width="75px" style="margin-top: 20px">
            <el-form-item label="日期"><p class="orderMessage">{{ order.date }}</p>
            </el-form-item>
            <el-form-item label="时间段"><p class="orderMessage">{{ order.time }}</p>
            </el-form-item>
            <el-form-item label="场地名"><p class="orderMessage">{{ order.court }}</p>
            </el-form-item>
            <el-form-item label="价格"><p class="orderMessage">{{ order.amount }}元/2小时</p>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div style="text-align: center;margin-top: 20px">
        <el-button type="primary" @click="paying">已完成支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "selectCourt",
  data() {
    return {
      orderDialog: false,
      categoryList: [],
      date: [],
      timeQuantumList: [
        "08:00-10:00",
        "10:00-12:00",
        "12:00-14:00",
        "14:00-16:00",
        "16:00-18:00",
        "18:00-20:00",
        "20:00-22:00",
      ],
      courtTable: [],
      categoryChoice: "",
      timeChoice: "",
      courtChoice: "",
      timeQuantumChoice: "",
      courtList: [],
      orderList: [],

      order: {
        userId: "",//用户id
        date: "",//日期
        time: "",//时间段
        courtId: "",//场地id
        court: "",//场地名（删除）
        amount: "",//价格
        categoryId: "",//类别id
      },
    }
  },
  computed: {
    getCellStyles() {
      return (row, columnName) => {
        // 根据不同的条件计算样式对象
        if (row[columnName] === '已被预订') {
          return {
            backgroundColor: 'red',
            color: 'silver'
          };
        } else if (row[columnName] === '未预订') {
          return {
            backgroundColor: 'lightgreen',
            color: 'black',
          };
        } else if (row[columnName] === '不可预订') {
          return {
            backgroundColor: 'gray',
            color: 'white',
          };
        } else {
          return {
            backgroundColor: 'white',
            color: 'black',
          };
        }
      };
    },
  },
  methods: {
    paying() {
      this.$delete(this.order, "court")
      let url = "http://localhost:9999/zx-order/booking/addNew"
      let data = this.qs.stringify(this.order);
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('userJwt')}}
      ).post(url, data).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.loadOrder()
        } else {
          this.$message({message: jsonResult.message, type: "error"})
        }
      })
      this.orderDialog = false;
    },
    cellHandleclick(row, column) {
      if (localStorage.getItem("userId") === null || localStorage.getItem("userId") === "") {
        this.$message({message: "用户未登录，请先登录", type: "warning"})
        this.$emit("login")
        return;
      }
      if (row[column.property] === "已被预订") {
        this.$message({message: column.property + "在" + row["time"] + "已被租赁", type: "warning"})
        return;
      }
      if (row[column.property] === "不可预订") {
        this.$message({message: column.property + "在" + row["time"] + "已不可租赁", type: "warning"})
        return;
      }
      this.order.time = row["time"]
      this.order.court = column.property
      this.order.date = this.timeChoice
      this.order.userId = localStorage.getItem("userId")
      if (Array.isArray(this.categoryChoice)) {
        this.order.categoryId = this.categoryChoice[0]
      } else {
        this.order.categoryId = this.categoryChoice
      }
      for (let i = 0; i < this.courtList.length; i++) {
        if (this.courtList[i].name === column.property) {
          this.order.courtId = this.courtList[i].id;
        }
      }
      let url = "http://localhost:9999/zx-court/court/selectDetails?id=" + this.order.courtId;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('userJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.order.amount = jsonResult.price
        }
      })
      this.orderDialog = true;
    },
    loadCourt() {
      if (this.categoryChoice !== "" && this.timeChoice !== "") {
        let url = "http://localhost:9999/zx-court/court/groupList?id=" + this.categoryChoice
        this.axios.get(url).then((response) => {
              let jsonResult = response.data;
              if (jsonResult.state === 200) {
                jsonResult = jsonResult.data;
                if (jsonResult.length >= 1) {
                  this.courtList = jsonResult;
                  this.loadOrder();
                } else {
                  this.courtList = [];
                  this.courtList.push({"name": "暂无运动场地可用"})
                }
              }
            }
        )
      }
    },
    loadOrder() {
      let date = new Date();
      let year = date.getFullYear();
      let month = String(date.getMonth() + 1).padStart(2, '0');
      let day = String(date.getDate()).padStart(2, '0');
      let nowDay = `${year}-${month}-${day}`;
      for (let i = 0; i < this.courtList.length; i++) {
        for (let j = 0; j < this.orderList.length; j++) {
          this.$delete(this.orderList[j], this.courtList[i].name)
        }
      }
      let url = "http://localhost:9999/zx-order/booking/prepareList?categoryId=" + this.categoryChoice + "&date=" + this.timeChoice
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('userJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          for (let i = 0; i < this.orderList.length; i++) {
            for (let j = 0; j < this.courtList.length; j++) {
              if (this.timeChoice === nowDay) {
                let targetTime = new Date();
                targetTime.setHours(this.orderList[i].time.split("-")[0].split(":")[0])
                targetTime.setMinutes(this.orderList[i].time.split("-")[0].split(":")[1])
                if (date.getTime() > targetTime.getTime()) {
                  this.$set(this.orderList[i], this.courtList[j].name, "不可预订")
                }
              }
              if (jsonResult.length >= 1) {
                for (let k = 0; k < jsonResult.length; k++) {
                  if (jsonResult[k].courtId === this.courtList[j].id && jsonResult[k].time === this.orderList[i].time) {
                    if (this.orderList[i][this.courtList[j].name] !== "不可预订") {
                      this.$set(this.orderList[i], this.courtList[j].name, "已被预订")
                    }
                  }
                  if (this.orderList[i][this.courtList[j].name] !== "已被预订" && this.orderList[i][this.courtList[j].name] !== "不可预订") {
                    this.$set(this.orderList[i], this.courtList[j].name, "未预订")
                  }
                }
              } else if (jsonResult.length < 1) {
                if (this.orderList[i][this.courtList[j].name] !== "已被预订" && this.orderList[i][this.courtList[j].name] !== "不可预订") {
                  this.$set(this.orderList[i], this.courtList[j].name, "未预订")
                }
              }
            }
          }
        }
      })
    },
    loadCategory() {
      let url = "http://localhost:9999/zx-court/category/treeList"
      this.axios.create(
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data
          this.categoryList = jsonResult;
          this.categoryChoice = this.categoryList[0].value;
        }
      })
    },
    loadTime() {
      let currentDate = new Date();
      for (let i = 0; i < 7; i++) {
        let date = new Date(currentDate.getTime());
        date.setDate(date.getDate() + i);
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0');
        let day = String(date.getDate()).padStart(2, '0');
        let formattedDate = `${year}-${month}-${day}`;
        this.date.push(formattedDate);
        this.timeChoice = this.date[0]
      }
    },
  },
  mounted() {
    this.loadCategory();
    this.loadTime();
    for (let i = 0; i < this.timeQuantumList.length; i++) {
      this.orderList.push({"time": this.timeQuantumList[i]});
    }

  },
  watch: {
    categoryChoice() {
      this.loadCourt()
    },
    timeChoice() {
      this.loadCourt()
    },
  }
}
</script>

